# from django.core.cache import cache
from rest_framework import viewsets, mixins
from rest_framework.decorators import action
from rest_framework.response import Response

from cart.models import CartModel
from cart.serializers import CartSerializer
from utils.auth import CustomAuthentication


class CartView(viewsets.GenericViewSet,
               mixins.ListModelMixin,
               mixins.UpdateModelMixin):
    queryset = CartModel.objects.all()
    serializer_class = CartSerializer
    authentication_classes = (CustomAuthentication, )

    # 用户认证
    # authentication_classes = (UserAuth,)

    def list(self, request, *args, **kwargs):

        user = request.user
        queryset = self.get_queryset().filter(user=user)
        serializer = self.get_serializer(queryset, many=True)
        for _ in serializer.data:
            pass
        carts = CartModel.objects.filter(user=user).all()
        for _ in carts:
            pass
        res = {
            'carts': serializer.data,
        }
        """
            {
              "code": 200,
              "msg": "success",
              "data": [
                {
                  "cart_id": "",
                  "user_id": "",
                  "shop": [],
                  "foods": [],
                  "number": "",
                  "is_select": ""
                }
                {}
              ]
            }
        """

        return Response(res)

    def update(self, request, *args, **kwargs):
        # 修改当前选择的商品的is_select字段
        instance = self.get_object()
        instance.is_select = 1 if instance.is_select == 0 else 0
        instance.save()
        res = {
            'msg': '选择操作成功！'
        }
        return Response(res)

    @action(detail=False, methods=['POST'])
    def add_cart(self, request):
        user_id = request.data.get('user_id')
        shop_id = request.data.get('shop_id')
        food_id = request.data.get('food_id')
        user_cart = CartModel.objects.filter(user_id=user_id, shop_id=shop_id, food_id=food_id).first()
        if user_cart:
            user_cart.number += 1
            user_cart.save()
        else:
            CartModel.objects.create(user_id=user_id, shop_id=shop_id, food_id=food_id)
        res = {'msg': '添加商品成功'}
        return Response(res)

    @action(detail=False, methods=['POST'])
    def sub_cart(self, request):
        user_id = request.data.get('user_id')
        shop_id = request.data.get('shop_id')
        food_id = request.data.get('food_id')
        user_cart = CartModel.objects.filter(user_id=user_id, shop_id=shop_id, food_id=food_id).first()
        if user_cart.number == 1:
            user_cart.delete()
        else:
            user_cart.number -= 1
            user_cart.save()
        res = {'msg': '删减商品成功'}
        return Response(res)
